package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.UserReceviveSound;
import com.tanhua.dubbo.api.mongo.UserReceviveSoundApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@Service(timeout = 10000)
public class UserReceviveSoundApiImpl implements UserReceviveSoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public UserReceviveSound findByUid(Long id) {
        Query query = new Query(Criteria.where("userId").is(id));
        return mongoTemplate.findOne(query, UserReceviveSound.class);
    }

    @Override
    public Integer reduceRemaining(Long id) {
        Query query = new Query(Criteria.where("userId").is(id));
        Update update = new Update();
        update.inc("remainingTimes",-1);
        mongoTemplate.updateFirst(query,update, UserReceviveSound.class);
        UserReceviveSound one = mongoTemplate.findOne(query, UserReceviveSound.class);
        return one.getRemainingTimes();
    }

    @Override
    public void save(Long id) {
        UserReceviveSound userReceviveSound = new UserReceviveSound(null,id,2);

        mongoTemplate.save(userReceviveSound);
    }

    @Override
    public void clearRemaining() {
        Update update = new Update();
        update.set("remainingTimes",5);
        mongoTemplate.updateMulti(new Query(),update, UserReceviveSound.class);
    }
}
